// server
package main

import (
	"encoding/json"
	"fmt"
	"fury/httpserver"
	"net/http"
	"strings"
	"time"

	log "github.com/cihub/seelog"
)

const SERVER_NAME string = "ChatService"
const SERVER_ADDR string = ":6616"

var hostlist = make([]string, 0, 10)
var roomMap = make(map[string]int)
var (
	chatService *httpServer.HttpServer
)

func main() {
	chatService = httpServer.CreateHttpServer(SERVER_NAME, SERVER_ADDR)
	chatService.AddRouter("/", defaultRouter)
	chatService.AddRouter("/openRoom", openRoom)
	chatService.AddRouter("/updateUser", updateUser)
	chatService.Start()
}

func defaultRouter(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()
	log.Info("form==> " + r.Form.Encode())
	log.Info("path==> " + r.URL.Path)
	log.Info("schema==> " + r.URL.Scheme)
	fmt.Fprintf(w, "Response at time : "+time.Now().String())
}

func updateUser(w http.ResponseWriter, r *http.Request) {
	error := r.ParseForm()
	if error != nil {
		fmt.Fprintf(w, "{\"error\":\"参数错误\"}\"")
		return
	}
	if len(r.Form) > 0 {
		userid := r.Form.Get("userid")
		/*token := r.Form.Get("tok/*en")
		askusertype := r.Form.Get("askusertype")*/
		if userid != "" {
			existed := checkHostList(userid)
			if !existed {
				hostlist = append(hostlist, userid)
				fmt.Fprint(w, updateUserResponse(1, "用户升级成功"))
			} else {
				fmt.Fprint(w, updateUserResponse(0, "用户已升级过"))
			}
		} else {
			fmt.Fprint(w, updateUserResponse(0, "用户id不能为空"))
		}

	}
}

func openRoom(w http.ResponseWriter, r *http.Request) {
	error := r.ParseForm()
	if error != nil {
		fmt.Fprintf(w, "{\"error\":\"参数错误\"}\"")
		return
	}
	userid := r.Form.Get("userid")
	if userid == "" {
		fmt.Fprint(w, openRoomResponse(0, "用户id不能为空", -1))
		return
	}
	if checkHostList(userid) {
		roomMap[userid] = len(roomMap)
		fmt.Fprint(w, openRoomResponse(1, "请先升级用户权限", 0))
	} else {
		fmt.Fprint(w, openRoomResponse(0, "请先升级用户权限", -1))
	}

}

func checkHostList(userid string) bool {
	existed := false
	for i := 0; i < len(hostlist); i++ {
		if strings.EqualFold(hostlist[i], userid) {
			existed = true
			break
		}
	}
	return existed
}

func updateUserResponse(code int, message string) string {
	result := NewUserUpdate()
	result.AskStatus = code
	result.Message = message
	bytes, _ := json.Marshal(result)
	return string(bytes)
}

func openRoomResponse(code int, message string, roomid int) string {
	result := NewOpenRoom()
	result.code = code
	result.message = message
	result.roomid = roomid
	bytes, _ := json.Marshal(result)
	return string(bytes)
}

type userUpdate struct {
	AskStatus int    `json:"askstatus"`
	Message   string `json:"message"`
}

func NewUserUpdate() *userUpdate {
	return &userUpdate{}
}

type roomOpen struct {
	code    int    `json:"code"`
	message string `json:"message"`
	roomid  int    `json:"roomid"`
}

func NewOpenRoom() *roomOpen {
	return &roomOpen{}
}
